package com.itany.shop.service.impl;

import com.itany.shop.constant.DictConstant;
import com.itany.shop.dao.ProductDao;
import com.itany.shop.entity.Product;
import com.itany.shop.exception.ProductNotExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.ProductService;
import com.itany.shop.util.PageInfo;
import com.itany.shop.util.ParameterUtil;

import java.util.List;

/**
 * @author 石小俊
 */
public class ProductServiceImpl implements ProductService {
    private ProductDao productDao = (ProductDao) ObjectFactory.getObject("productDao");

    @Override
    public List<Product> findAll() {
        return productDao.selectAll();
    }

    @Override
    public List<Product> findPage(String pageNo, String pageSize) throws ProductNotExistException {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.PRODUCT_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.PRODUCT_DEFAULT_PAGE_SIZE;
        }
        List<Product> products = productDao.selectPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        if (products.isEmpty()) {
            throw new ProductNotExistException("超出了页码范围");
        }
        return products;
    }

    @Override
    public PageInfo<Product> findPageInfo(String pageNo, String pageSize) throws ProductNotExistException {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.PRODUCT_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.PRODUCT_DEFAULT_PAGE_SIZE;
        }
        List<Product> products = productDao.selectPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        // 获取总记录条数
        int total = productDao.selectCount();
        PageInfo<Product> productPageInfo = new PageInfo<>(total, Integer.parseInt(pageNo), Integer.parseInt(pageSize), products);
        if (products.isEmpty()) {
            throw new ProductNotExistException("超出了页码范围,当前最大页数为:" + productPageInfo.getPages());
        }
        return productPageInfo;
    }
}
